package com.xyz.basesdk.helpers;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author mac
 *         on 2018/3/1.
 */

public class ThreadPoolHelper implements RejectedExecutionHandler {

    private final ThreadPoolExecutor poolExecutor;

    private static class ThreadPoolHolder {
        static ThreadPoolHelper instance = new ThreadPoolHelper();
    }

    public static ThreadPoolHelper getInstance() {
        return ThreadPoolHolder.instance;
    }

    private ThreadPoolHelper() {
        int corePoolSize = 2;
        int maximunPoolSize = 4;
        long keepAliveTime = 3 * 60 * 1000;
        poolExecutor = new ThreadPoolExecutor(corePoolSize, maximunPoolSize,
                keepAliveTime, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<Runnable>(),
                Executors.defaultThreadFactory(), this);
    }


    public void execute(Runnable runnable) {
        poolExecutor.execute(runnable);
    }

    public void shutDown() {
        poolExecutor.shutdown();
    }

    public void shutDownNow() {
        poolExecutor.shutdownNow();
    }

    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {

    }
}
